<template>
    <view class="page-create-index">
        <view class="menu">
            <u-row gutter="16">
				<u-col span="4" v-for="(item,index) in menu.list" :key="index">
					<view class="text-center" :class="index == 0 ? 'current' : ''" @click="changeMenu(item)">{{ item.name }}</view>
				</u-col>
            </u-row>
        </view>
        <view class="fly-title">活动信息</view>
        <view class="form-block mb-2">
            <u-form ref="form1" label-width="160rpx">
                <u-form-item label="活动方式" right-icon="arrow-right">
                    <u-input v-model="form.activitiesMethodName" disabled placeholder="请选择" input-align="right"  @click="showActionSheet('activitiesMethod')" />
                </u-form-item>
                <u-form-item label="活动类型" right-icon="arrow-right" :border-bottom="false">
                    <u-input v-model="form.activitiesTypeName" readonly placeholder="请选择" input-align="right" @click="showActionSheet('activitiesType')" />
                </u-form-item>
            </u-form>
        </view>
        <view class="form-block">
            <u-form ref="form2" label-width="160rpx">
                <u-form-item label="活动名称">
                    <u-input v-model="form.activitiesName" placeholder="请输入" input-align="right" />
                </u-form-item>
                <u-form-item label="活动时间" right-icon="arrow-right">
                    <u-input v-model="form.startTime"  disabled placeholder="请选择" input-align="right" @click="picker.timeShow = true" />
                </u-form-item>
                <u-form-item label="选择城市" right-icon="arrow-right">
                    <u-input v-model="form.cityName"  disabled placeholder="请选择" input-align="right" @click="picker.regionShow = true"/>
                </u-form-item>
                <u-form-item label="活动地址" right-icon="arrow-right">
                    <u-input v-model="form.address" disabled placeholder="请输入" input-align="right" @click="openMap" />
                </u-form-item>
                <!-- <u-form-item label="门牌号">
                    <u-input v-model="form.room" placeholder="请输入" input-align="right" />
                </u-form-item> -->
                <u-form-item label="现场签到" :border-bottom="false">
                    <template v-slot:right>
                        <u-switch v-model="form.isCheckinRequired" size="40" active-color="#67E5C2"></u-switch>
                    </template>
                </u-form-item>
            </u-form>
            <view class="sign-tips">现场签到需在活动开始前后一小时进行现场签到，未按时签到会扣取信用分5分</view>
        </view>
        <view class="mx-4 my-2"></view>
        <view class="form-block mb-2">
            <u-form ref="form2" label-width="160rpx">
                <u-form-item label="活动人数">
                    <u-input v-model="form.maxParticipants" placeholder="请输入" type="number" input-align="right" />
                </u-form-item>
                <u-form-item label="活动封面" label-position="top">
                    <u-upload :action="upload.api" :header="upload.header" :file-list="upload.coverImageUrl" :max-count="1" :multiple="false" @on-success="coverSuccess" @on-error="coverError" :auto-upload="true"></u-upload>
                </u-form-item>
                <u-form-item label="活动详情"  label-position="top">
                    <u-input v-model="form.description" placeholder="为了让大家更好地了解该活动，请介绍一下活动亮点、行程规划和注意事项等活动详情内容，限1千字" type="textarea" :auto-height="true" />
                </u-form-item>
                <u-form-item label="讨论问题1"  label-position="top">
                    <u-input v-model="form.discussionQuestions1" placeholder="请输入讨论问题，限100字" type="textarea" :auto-height="true" />
                </u-form-item>
                <u-form-item label="讨论问题2"  label-position="top">
                    <u-input v-model="form.discussionQuestions2" placeholder="请输入讨论问题，限100字" type="textarea" :auto-height="true" />
                </u-form-item>
                <u-form-item label="讨论问题3"  label-position="top" :border-bottom="false">
                    <u-input v-model="form.discussionQuestions3" placeholder="请输入讨论问题，限100字" type="textarea" :auto-height="true" />
                </u-form-item>
            </u-form>
        </view>
        <view class="fly-title">联系方式</view>
        <view class="form-block">
            <u-form ref="form2" label-width="160rpx">
                <!-- <u-form-item label="手机号码">
                    <u-input v-model="form.phone" placeholder="请输入" />
                </u-form-item> -->
                <u-form-item label="活动群二维码" label-width="180rpx" label-position="top">
                    <u-upload :action="upload.api" :header="upload.header" :file-list="upload.groupQrcodeUrl" :max-count="1" :multiple="false" @on-success="groupSuccess" @on-error="groupError" :auto-upload="true"></u-upload>
                </u-form-item>
                <u-form-item label="个人二维码" label-position="top" :border-bottom="false">
                    <u-upload :action="upload.api" :header="upload.header" :file-list="upload.organizerWechatQrcodeUrl" :max-count="1" :multiple="false" @on-success="organizerSuccess" @on-error="organizerError" :auto-upload="true"></u-upload>
                </u-form-item>
            </u-form>
        </view>
        <view class="fly-bottom-bar">
            <view class=" content">
                <u-checkbox-group>
                    <u-checkbox v-model="isAgree" label-size="26rpx" active-color="#67E5C2">我已阅读并同意<text class="c-cyan" @click.stop="showAgree">《发起活动知情同意书》</text></u-checkbox>
                </u-checkbox-group>
                <view class="flex-between mt-2">
                    <view class="fl" @click="submitForm(0)">
                        <u-image :src="proxy.$icon.draft" width="48rpx" height="44rpx" class="display-inline"></u-image>
                        <view class="c-grey9">存草稿</view>
                    </view>
                    <view class="fr flex-between">
                        <u-button class="btn-deepCyan" block :loading="btnLoading" @click="submitForm(1)">发起活动</u-button>
                    </view>
                </view>
            </view>
        </view>
        <u-action-sheet :list="actionSheet.list" v-model="actionSheet.isShow" @click="selectActionSheet"></u-action-sheet>
        <u-picker v-model="picker.timeShow" mode="time" :params="picker.timeParams" :default-time="picker.defaultTime" @confirm="getTime"></u-picker>
        <u-picker v-model="picker.regionShow" mode="region" :params="picker.regionParams" @confirm="getRegion"></u-picker>
        <fly-tabbar ref="refFlyTabbar" :current="2"/>
    </view>
</template>
<script setup lang="ts">
import dayjs from 'dayjs';
import {apiUrl, fileUrl} from '@/static/js/config';
import FlyTabbar from '@/components/FlyTabbar/index.vue'
const refFlyTabbar = ref();
import { onShow, onLoad } from '@dcloudio/uni-app';
import { useAppStore } from '@/stores/app';
import { useOptionData } from '@/stores/optionData';
import { reactive } from 'vue';
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const appStore = useAppStore();
const optionDataStore = useOptionData();
let pageParams = reactive({id: null});
let isAgree = ref(false);
const menu = reactive({
    current: 0,
    list:[
        {name: '发起活动'},
        {name: '活动草稿', url: '/pages/create/draft'},
        {name: '活动模板', url: '/pages/create/template'},
    ]});
let btnLoading = ref(false);
let form = reactive({
    "id": null,
    "startTime": "",
    "coverImageUrl": "",
    "activitiesName": "",
    "activitiesMethod": "",
    "activitiesMethodName": "",
    "platform": "",
    "maxParticipants": null,
    "groupQrcodeUrl": "",
    "organizerWechatQrcodeUrl": "",
    "description": "",
    "recommendations": "",
    "activitiesType": null,
    "activitiesTypeName": '',
    "discussionQuestions1": "",
    "discussionQuestions2": "",
    "discussionQuestions3": "",
    "abcode": "",
    cityName: null,
    "address": "",
    "checkinAddress": "",
    "isCheckinRequired": null,
    "initiatorUserId": null,
    "guildId": null,
    "approverUserId": null,
    "status": 0 ,
    "latitude": null,
    "longitude": null,
});
let actionSheet = reactive({
    isShow: false,
    type: null,
    list: [],
});
let upload = reactive({
    // api: 'http://book.caochuanxi.com/api/admin/sys-file/upload',
    api: apiUrl + '/admin/sys-file/upload',
    header: {
        Authorization: `Bearer ${uni.getStorageSync('accessToken')}`,
        "TENANT-ID": 1,
        'CLIENT-TOC': 'Y'
    },
    list: [],
    coverImageUrl: [],
    organizerWechatQrcodeUrl: [],
    groupQrcodeUrl: []
});
let picker = reactive({
    timeShow: false,
    defaultTime: dayjs().format('YYYY-MM-DD HH:mm'),
    timeParams:{
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true,
        second: false,
    },
    regionShow: false,
    regionParams:{
        province: true,
        city: true,
        area: false
    }
});
let optionData = reactive({});
const getInitData = async () => {
    form.initiatorUserId = appStore.userInfo.userId;
    form.guildId = '1804169217'; //appStore.userInfo.guildId;
    optionData.activitiesType = await optionDataStore.getDictList('activitie_type');
    optionData.activitiesMethod = await optionDataStore.getDictList('activitie_method');
    getDetail();
}
const getDetail = () => {
    if(!pageParams.id){
        return;
    }
    proxy.$http('get', '/admin/activities/' + pageParams.id, {}, (data,msg) => {
        proxy.$util.resetForm(form, data);
        form.activitiesTypeName = proxy.$util.setName(String(data.activitiesType), optionData.activitiesType);
        form.activitiesMethodName = proxy.$util.setName(String(data.activitiesMethod), optionData.activitiesMethod);
        form.cityName = proxy.$util.getCityName(data.abcode);
        upload.coverImageUrl = [apiUrl + form.coverImageUrl];
    });
};
const changeMenu = item => {
    if(item.url){
        proxy.$util.gotoPage(item.url);
    }
};
const showActionSheet = (type) => {
    actionSheet.isShow = true;
    actionSheet.type = type;
    actionSheet.list= optionData[type];
};
const selectActionSheet = (val) => {
    form[actionSheet.type] = actionSheet.list[val].id;
    form[actionSheet.type + 'Name'] = actionSheet.list[val].text;
};
const getTime = (val) => {
    form.startTime = val.year + '-' + val.month + '-' + val.day + ' ' + val.hour + ':' + val.minute + ':00' ;//+ ':' + val.second;
};
const getRegion = val => {
    form.abcode = val.city.code;
    form.cityName = val.city.name;
}
const openMap = () => {
    uni.chooseLocation({
        success: res => {
            form.longitude = res.longitude;
            form.latitude = res.latitude;
            form.address = res.address;
        },
        fail: error => {
            console.log(error);
        }
    })
};
const coverSuccess = (res) => {
    form.coverImageUrl = res.data.url;
}
const coverError = (res) => {

}
const groupSuccess = (res) => {
    form.groupQrcodeUrl = res.data.url;
}
const groupError = (res) => {

}
const organizerSuccess = (res) => {
    form.organizerWechatQrcodeUrl = res.data.url;
}
const organizerError = (res) => {

}
const uploadSuccess = (data, index, lists, name) => {
    console.log(data);
    // upload.coverImageUrl.push({url: data.data.url});
    console.log(upload.coverImageUrl);
}
const uploadError = (res, index, lists, name) => {
    console.log(res);
    // console.log(upload.coverImageUrl);
};
const showAgree = () => {
    uni.showModal({
        title: '知情同意书',
        content: '这是一个模态弹窗',
        confirmText: '同意',
        success: function (res) {
            if (res.confirm) {
                isAgree.value = true;
            } else if (res.cancel) {
                console.log('用户点击取消');
            }
        }
    });
}
const verifyForm = () => {
    if(!proxy.$verify.null(form.activitiesMethod, '请选择活动方式')){
        return false;
    }
    if(!proxy.$verify.null(form.activitiesType, '请选择活动类型')){
        return false;
    }
    if(!proxy.$verify.null(form.activitiesName, '请填写活动名称')){
        return false;
    }
    if(!proxy.$verify.null(form.startTime, '请选择活动时间')){
        return false;
    }
    if(!proxy.$verify.null(form.abcode, '请选择城市')){
        return false;
    }
    if(!proxy.$verify.null(form.address, '请选择活动地址')){
        return false;
    }
    if(!proxy.$verify.null(form.coverImageUrl, '请上传活动封面')){
        return false;
    }
    if(!proxy.$verify.null(form.description, '请填写活动详情')){
        return false;
    }
    if(!isAgree.value){
        uni.$u.toast('请阅读并同意《发起活动知情同意书》');
        return false;
    }
    return true;
}
const submitForm = (status) => {
    if(!verifyForm()){return;}
    let params = JSON.parse(JSON.stringify(form));
    params.status = status;
    params.isCheckinRequired = form.isCheckinRequired ? 1 : 0;
    btnLoading.value = true;
    proxy.$http('post', '/admin/activities', params, (data,msg) => {
        btnLoading.value = false;
        uni.$u.toast('提交成功');
        proxy.$util.gotoPage('/pages/home/index');
    },msg => {
        btnLoading.value = false;
    })
}
onLoad(e => {
    pageParams = e;
});
onShow(() => {
    getInitData();
})
</script>